package avicit.bdp.dgs.qa.service.algo.raw.data.pcm.checker;

import avicit.bdp.dgs.qa.service.algo.raw.data.pcm.utils.S3Utils;
import avicit.platform6.core.exception.BusinessException;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Map;
import java.util.UUID;

/**
 * @金航数码科技有限责任公司
 * @作者：developer
 * @邮箱：developer@avic-digital.com
 * @创建时间： 2023-11-01
 * @类说明：PCMFileChecker
 * @修改记录：
 * @注意事项：
 * @主要功能：pcm文件检测checker
 */
public class PCMFileChecker {
    private static final Logger logger = LoggerFactory.getLogger(PCMFileChecker.class);

    /**
     * PCM校验方法
     *
     * @param map
     */
    public static void check(Map<String, Object> map) {
        long start = System.currentTimeMillis();

        try {
            Map<String, Object> inputParamsMap = MapUtil.get(map, "inputParams", Map.class);
            Map<String, Object> outputParamsMap = MapUtil.get(map, "outputParams", Map.class);
            String icdFilePath = MapUtil.getStr(inputParamsMap, "icdFilePath", "");
            if (StrUtil.isBlank(icdFilePath)) {
                throw new BusinessException("ICD文件未输入！");
            }

            String inputFilePaths = MapUtil.getStr(inputParamsMap, "inputFilePath", "");
            if (StrUtil.isBlank(inputFilePaths)) {
                throw new BusinessException("数据文件未输入！");
            }

            String groupParams = MapUtil.getStr(inputParamsMap, "groupParams", "");
            String inputType = MapUtil.getStr(inputParamsMap, "inputType", "local");
            String[] filePaths = inputFilePaths.split(",");
            PCMConfigReader config = new PCMConfigReader(icdFilePath, inputParamsMap);
            PCMDataReader reader = new PCMDataReader(config);

            // 输入文件方式
            if (inputType.equalsIgnoreCase("local")) {
                for (String filePath : filePaths) {
                    InputStream dataSteam = null;
                    try {
                        for (int i = 0; i < config.getPcmHeadInfo().getStream_number(); i++) {
                            dataSteam = Files.newInputStream(Paths.get(filePath));
                            reader.readDataFrame(dataSteam, i, groupParams, outputParamsMap);
                        }
                    } catch (Exception e) {
                        logger.error("文件校验失败", e);
                        throw new BusinessException(e.getMessage() + ",文件校验失败");
                    }
                    IoUtil.close(dataSteam);
                }
            } else if (inputType.equalsIgnoreCase("minio")) {
                String endpoint = MapUtil.getStr(inputParamsMap, "endPoint", "http://127.0.0.1:9000");
                String accessKey = MapUtil.getStr(inputParamsMap, "accessKey", "minioadmin");
                String secretKey = MapUtil.getStr(inputParamsMap, "secretKey", "minioadmin");
                String bucketName = MapUtil.getStr(inputParamsMap, "bucketName", "test");

                for (String filePath : filePaths) {
                    InputStream dataSteam = null;
                    String fileName = /*"/tmp/" + */UUID.randomUUID() + "_" + FileUtil.getName(filePath);
                    try {
                        // 如果不下载到本地，通过远程读取oss对象流，校验有问题
                        S3Utils.download(endpoint, accessKey, secretKey, bucketName, filePath, fileName);
                        for (int i = 0; i < config.getPcmHeadInfo().getStream_number(); i++) {
                            dataSteam = Files.newInputStream(Paths.get(fileName));
                            reader.readDataFrame(dataSteam, i, groupParams, outputParamsMap);
                        }
                    } catch (Exception e) {
                        logger.error(String.format("下载文件[%s]到本地失败，校验失败。endPoint:%s,accessKey:%s,secretKey:%s,bucketName:%s,objectName:%s",
                                filePath, endpoint, accessKey,secretKey, bucketName, filePath), e);
                        throw new BusinessException(String.format("下载文件[%s]到本地失败.", filePaths));
                    } finally {
                        FileUtil.del(fileName);
                        IoUtil.close(dataSteam);
                    }
                }
            }

            logger.info("用时：" + (System.currentTimeMillis() - start));
        } catch (Exception e) {
            throw new BusinessException(e.getMessage());
        }
    }
}
